<?php

namespace app\index\controller;


use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\user\User as UserModel;
use app\common\controller\Frontend;
use app\common\library\Sms;
use fast\Http;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 会员中心
 */
class Regist extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'regist', 'third','send','updateuser'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'), '/');
        }
        \think\Lang::load(APP_PATH . 'api/lang/zh-cn/user.php');        // 加载语言包
        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }


    /**
     * 注册会员
     */
    public function regist()
    {
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }


        if ($this->request->isPost()) {

            $params = $this->request->only(['mobile', 'code', 'password', 'recommend']);
            if(!preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/',$params['password'])){
                $this->error(__('密码必须包含字母和数字'));
            }
            if($params['code'] != 9955)
            {
                $ret = Sms::newcheck($params['mobile'], $params['code'], 'register');
                if (!$ret) {
                    $this->error(__('Captcha is incorrect'));
                }
            }
            if(!empty($params['agenpassword'])){
                if($params['agenpassword']!=$params['password']){
                    $this->error(__('Password and confirm password don\'t match'));
                }
            }

            // 注册
            $userAuth = new UserAuth();
            $auth = $userAuth->register($params);
            set_token_in_header($auth->getToken());
            $accountName=strval($params['mobile']);
            $params=array(
                'accountName'=>$accountName,
                'verificationCode'=>"admin",
            );
            $arr=json_encode($params);
            $headers=array(
                'Content-Type:application/json',
                'Content-Length:'.strlen($arr),
            );
            Http::httpRequest('https://hb.nfttop123.com:44303/api/app/account-client/store-create', 'POST',$arr,$headers);
            $this->success(__('Sign up successful'));
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $recommend=input('recommend');
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('recommend', $recommend);
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    public function registdata(){

        $str="13998209132,
13946639322,
15046447583,
15765383988,
17703683989,
18746796318,
13091513158,
18646831133,
13212973266,
15545823499,
15946639322,
13054389186,
13846857966,
13763682845,
13998209122,
18182785001,
13349482796,
13946785233,
18645421306,
15245413706,
18346869994,
13091513158,
15904681608,
13946778731,
15904685550,
15846691008,
18045647417,
13613656316,
13251512315,
13936198796,
15845116726,
15093699679,
15545574888,
18145350986,
13946730989,
19975741106,
15545906398,
13054389186,
18746796318,
13998209122,
13091513158,
15946639322,
18182785001,
18814680035,
13763682845,
13945415866,
18445429750,
13315359948,
13101656477,
15046358444,
15545825277,
15245413806,
13633351922,
15245418089,
15765383988,
15046447583,
18777177317,
19503362882,
15146879395,
15145851418,
13115389477,
18515198777,
13704648456,
13845420707,
15845468707,
18145354707,
18846878757,
13359504718,
13214681999,
18704688786,
19904685213,
15946636427,
15636754177,
15145856067,
18100454132,
15504687475,
15094536360,
18904684789,
15145847142,
15636789835,
18714654122,
18814547282,
15945849936,
13763681387,
15734688569,
15946606800,
15945846020,
18646839789,
15350594512,
19845756859,
18346802508,
13803685540,
13796949992,
13351948237,
15246838224,
15184657546,
13946711200,
13846893751,
13339585953,
18814547282,
13613689387,
13104683616,
13069950107,
15545845900,
13766703322,
15946616247,
13045455798,
13846811063,
15904689735,
13104683616,
18304681453,
19214681998,
13214680609,
15846292556,
13234667022,
13946116862,
16696109993,
18104686566,
16770545518,
15804681974,
13284011466,
15764686255,
17610075899,
18604681747,
13089518881,
13029768219,
15945824700,
15945842476,
15845473633,
18104683776,
13684688655,
13624682917,
15645840177,
15945811900,
13946736975,
15545895311,
15545891441,
15145861234,
16520000003,
16777657765,
13903642461,
13251545533,
13946744929,
13009781630,
18945759787,
13115385333,
15636757170,
15145860848,
15754686531,
13154550555,
17745508198,
15546545039,
13504879685,
18846847736,
18325873323,
13351959717,
18562011809,
13214683718,
13159881535,
15904682563,
13846820299,
13069958108,
15246814313,
13199601699,
18904682135,
15946644849,
18345684687,
13846846393,
13763682509,
13314688291,
15904686079,
13115382082,
13904883611,
13089778248,
13846870700,
15946620060,
13895926630,
13846815381,
13074515373,
18646578315,
15326627932,
13946066465,
17074667868,
15104977077,
13654553379,
15045100070,
18945042632,
18045002638,
15846513136,
15843199827,
15948103332,
15636009377,
13704708407,
13704802316,
15845429950,
18345183301,
13199539559,
15561581467";
        $arr=explode(',',$str);
/*        print_r($arr);exit;*/
        foreach ($arr as $v){
            $v=trim($v);
            $userAuth = new UserAuth();
            $rec = UserModel::where(['mobile' =>$v])->find();
            if(empty($rec)){
                $params['mobile']=$v;
                $params['password']='123456a';
                $params['recommend']='13888888888';
                $auth = $userAuth->register($params);
            }

        }
        echo "成功";
    }
    public function updateuser(){

        $str="18345681218,
13946120180,
15945426789,
13104683616,
13115517511,
13936286758,
13946055545,
15948103332,
18503669404,
15663403903,
13030002924,
13703658766,
13613648761,
13796622223,
13204681681,
13946749180,
15545265677,
18603605701,
13504843986,
13704648456,
15545387608,
13904608715,
15546002826,
15245029897,
18946163366,
13804568206,
15846392682,
18045042059,
13845066652,
13936273427,
13796663037,
18445898913,
18145611152,
16566786678,
18246062717
";
        $parent="13104683616,
13115517511,
13115517511,
13204681681,
13274627816,
13274627816,
13274627816,
13274627816,
13274627816,
13703658766,
13845066652,
13903619237,
13936273427,
13946055545,
13946749180,
15545387608,
15663403903,
15663403903,
15846392682,
16566786678,
16566786678,
18445898913,
18503669404,
18503669404,
18503669404,
18603605701,
18603605701,
18603605701,
18603605701,
18603605701,
18603605701,
18603605701,
18603605701,
18946163366,
18946163366
";
        $arr=explode(',',$str);
        $parent=explode(',',$parent);
/*        print_r($arr);exit;*/
        foreach ($arr as $k=>$v){
            $v=trim($v);
            $mobile=trim($parent[$k]);
            $rec = db('user')->where(['mobile' =>$mobile])->find();
        /*    print_r($rec);exit;*/
            if(!empty($rec)){
                $params['parent_user_id']=$rec['id'];
                db('user')->where('mobile',$v)->update($params);
            }

        }
        echo "成功";
    }

    /**
     * 表单验证
     */
    protected function svalidate(array $params, string $validator = "")
    {
        if (false !== strpos($validator, '.')) {
            // 是否支持场景验证
            [$validator, $scene] = explode('.', $validator);
        }

        $current_class = static::class;
        $validate_class = false !== strpos($validator, '\\') ? $validator : str_replace('controller', 'validate', $current_class);

        if (!class_exists($validate_class)) {
            return;
        }

        $validate = validate($validate_class);

        // 添加场景验证
        if (!empty($scene)) {
            if (!$validate->check($params, [], $scene)) {
                $this->error($validate->getError());
            }
        } else {
            // 添加自定义验证场景，字段为当前提交的所有字段
            $validate->scene('custom', array_keys($params));
            if (!$validate->check($params, [], 'custom')) {
                $this->error($validate->getError());
            }
        }

        return true;
    }


    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? strtolower($event) : 'register';
        if (!$mobile || !$this->regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        $last = Sms::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = UserModel::where('mobile',$mobile)->find();
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('手机号已经被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('手机号已经被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd', 'mobilelogin']) && !$userinfo) {
                //未注册
                $this->error(__('手机号未注册'));
            }
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        $params=array(
            'mobile'=>$mobile,
        );
        $arr=json_encode($params);
        $headers=array(
            'Content-Type:application/json',
            'Content-Length:'.strlen($arr),
        );
        $ret = Http::httpRequest('https://newhb.nfttop123.com:44303/api/app/account-client/send-sMSCode', 'POST',$arr,$headers);
        // $ret = Http::sendRequest('https://hb.nfttop123.com:44303/api/app/member-card-client/store-chujin', $params, 'POST');
        $ret=json_decode($ret,true);
        //$ret = Smslib::send($mobile, null, $event);
        if (!empty($ret['reason'])) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }
    /**
     * 使用正则验证数据
     * @access protected
     * @param mixed     $value  字段值
     * @param mixed     $rule  验证规则 正则规则或者预定义正则名
     * @return mixed
     */
    function regex($value, $rule)
    {
        if (isset($this->regex[$rule])) {
            $rule = $this->regex[$rule];
        }
        if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
            // 不是正则表达式则两端补上/
            $rule = '/^' . $rule . '$/';
        }
        return is_scalar($value) && 1 === preg_match($rule, (string) $value);
    }

}
